package cn.tedu.boot21.controller;


import cn.tedu.boot21.entity.User;
import cn.tedu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {

    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        //得到数据库连接
        try(Connection conn = DBUtils.getConn();) {
            //注册
            String indexSql="select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(indexSql);
            ps.setString(1,user.getUsername());
            ResultSet indexRs = ps.executeQuery();
            if (indexRs.next()){
                return "用户已存在";
            }
            String insertSql = "insert into user values(null,?,?,?)";
            PreparedStatement insertPs = conn.prepareStatement(insertSql);
            insertPs.setString(1,user.getUsername());
            insertPs.setString(2,user.getPassword());
            insertPs.setString(3,user.getNick());
            insertPs.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);  //soutp回车
        try(Connection conn = DBUtils.getConn();) {
            String sql="select password from user where username=?";
            PreparedStatement ps =conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){//代表查询到了信息
                //判断用户输入的和查询到的数据是否一致
                if (rs.getString(1).equals(user.getPassword())){
                    return "等录成功";
                }
                return "密码错误";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在!";
    }
}
